<?php
require 'connection.php';
require 'ImageManipulator.php';
$GLOBALS['loginPageUrl'] = "http://projectx.x10.mx//login.php";
$GLOBALS['homePageUrl'] = "http://projectx.x10.mx/home.php";
$GLOBALS['logoutUrl'] = "http://projectx.x10.mx/accountValidator.php";
$GLOBALS['profilePage'] = "http://projectx.x10.mx/profile.php";
$GLOBALS['listingSalt'] = 678473527281691635271;
$GLOBALS['noPicImgUrl'] = "img/no-pic.jpeg";
function getResultArray($query, $pdo, $params=array()){
	$statement = $pdo->prepare($query);
	if(isset($params) && !empty($params)){
		foreach ($params as $key => $value) {
			$statement->bindValue($key, $value);
		}
	}
	$statement->execute();
	$array = $statement->fetchAll();
	return $array;
}

function registerExists($table, $fieldsAndValues, $pdo){
	$query = "SELECT * FROM $table WHERE ";
	$index = 0;
	foreach ($fieldsAndValues as $key => $value) {
		$query .= $table.".".str_replace(":", "", $key)."= $key";
		if(++$index < sizeof($fieldsAndValues)){
			$query .= " and ";
		}
	}
	$result = getResultArray($query,$pdo, $fieldsAndValues);
	return !empty($result);
}

//The keys in params must be preceded by semicolon -> :
function executeInsert($table, $params, $pdo){
	$index = 0;
	$columnNames = "";
	$values = "";
	foreach ($params as $key => $value) {
		$values .= $key;
		$columnNames .= str_replace(":", "", $key);
		if(++$index < sizeof($params)){
			$columnNames .= ",";
			$values .= ",";
		}
	}
	$query = "INSERT INTO $table ($columnNames) VALUES ($values)";
	$statement = $pdo->prepare($query);
	if($statement->execute($params)){
		return $pdo->lastInsertId();
	}else{
		return -1;
	}
}

function executeDelete($table, $paramsWhere, $pdo){
	$index = 0;
	$query = "DELETE FROM $table WHERE ";
	$whereString = "";
	foreach ($paramsWhere as $key => $value) {
		$whereString .= str_replace(":", "", $key)." = $key";
		if(++$index < sizeof($paramsWhere)){
			$whereString .= " and ";
		}
	}
	$query .= $whereString;
	$statement = $pdo->prepare($query);
	foreach ($paramsWhere as $key => $value) {
			$statement->bindValue($key, $value);
	}
	return $statement->execute();
}

function executeUpdate($table, $paramsSet, $paramsWhere, $pdo){
	$index = 0;
	$query = "UPDATE $table SET ";
	$setString = "";
	$whereString = "";
	foreach ($paramsSet as $key => $value) {
	 	$setString .= str_replace(":", "", $key)." = $key";
	 	if(++$index < sizeof($paramsSet)){
	 		$setString .= ",";
	 	}
	}

	foreach ($paramsWhere as $key => $value) {
		$whereString .= str_replace(":", "", $key)." = $key";
		if(++$index < sizeof($paramsWhere)){
			$whereString .= " and ";
		}
	}
	$query .= $setString;

	if(!empty($paramsWhere)){
		$query .= " WHERE ".$whereString;
	}

	$statement = $pdo->prepare($query);
	foreach ($paramsSet as $key => $value) {
			$statement->bindValue($key, $value);
	}
	foreach ($paramsWhere as $key => $value) {
			$statement->bindValue($key, $value);
	}
	return $statement->execute();
}

//Util File
// jS JsonString
function getArrayFromResut($result){

	$listing = array();
	$listing['pk'] = $result['pk'];
	$listing['encryptedPk'] = getHiddenListingPk($result['pk']);
	$listing['title'] = strtoupper($result['title']);
	$listing['imageUrl'] = getListingPictureNotLoggedIn($result['pk']);
	$listing['beds'] = trim($result['beds']);
	$listing['description'] = $result['description'];
	$listing['price'] = ((float)$result['price']);
	$listing['latitude'] = $result['latitude'];
	$listing['longitude'] = $result['longitude'];
	$listing['district'] = strtoupper($result['district']);
	return $listing;
}

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

function goToUrl($url){
	//header("Location: ".$url);
	echo "<script>window.location = '$url'</script>";
}

function isNumber($n){
	return is_numeric($n);
}

function checkUserLoggedIn(){
	if(isset($_SESSION['loggedin']) and $_SESSION['loggedin'] == true){
		return true;
	}
	return false;
}

function isLoggedIn(){
	return isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && getLoggedInUser() != "";
}

function getLoggedInUser(){
	return $_SESSION['userLoggedIn'];
}

function createDirectory($dir){
	if(!file_exists($dir)){
		mkdir($dir, 0755, true);
	}
	return $dir;
}
function moveFiles($files,$dir){
	$uploads_dir = $dir;
	$paths = array();
	if(empty($files)){
		return $paths;
	}
	foreach ($files as $key => $value) {
	    if ($value['error'] == UPLOAD_ERR_OK) {
	        $tmp_name = $value["tmp_name"];
	        //print(explode(".", $value["name"])[1]);
	        //$name = $files["pictures"]["name"][$key];
	        $dividedFileName = explode(".", $value["name"]);
	        $name = generateRandomString(7).".".$dividedFileName[sizeof($dividedFileName)-1];
	        move_uploaded_file($tmp_name, "$uploads_dir/$name");
	        $paths[$key] = "$uploads_dir/$name";
	    }
	}
	return $paths;
}

function getNewFilePath($path, $sufix = null)
{
	$newPath = dirname($path)."/".generateRandomString(7).".".explode(".", $path)[1];
	if($sufix != null)
	{
		$newPath = addSufixFilePath($newPath, $sufix);
	}
	return $newPath;
}

function additionalInformationExists($userId){
	$query = "SELECT * FROM user_info WHERE user_fk = :user_fk";
	$params = array(
		":user_fk"=>$userId
		);
	$result = getResultArray($query, $GLOBALS['pdo'], $params);
	//print_r($result);
	return !empty($result);
}

function getUserInformation($userId){
	$query = "SELECT user_info.*, user_gender.description AS 'gender'  FROM user_info INNER JOIN user_gender ON user_info.gender_fk = user_gender.pk  WHERE user_fk = :user_fk";
	$params = array(
		":user_fk"=>$userId
		);
	$result = getResultArray($query, $GLOBALS['pdo'], $params);
	$queryPicture = "SELECT * FROM user_picture WHERE user_picture.user_fk = :user_fk AND user_picture.main_picture = 1";
	$paramsPicture = array(
		":user_fk"=>$userId
		);
	$resultImg = getResultArray($queryPicture, $GLOBALS['pdo'], $paramsPicture);
	if(!empty($resultImg))
	{
		$result["first_image_url"] = $resultImg[0]['picture_url'];
	}
	return isset($result[0]) ? $result[0] : null;
}

function getUserPictures($userId, $getMain=false, $imgPk=null)
{
	$query = "SELECT * FROM user_picture WHERE user_picture.user_fk = :user_fk";
	if($getMain)
	{
		$query .= " AND main_picture = 1";
	}

	$params = array(
		":user_fk"=>$userId
		);
	if($imgPk != null)
	{
		$query .= " AND pk = :pk";
		$params[":pk"] = $imgPk;
	}
	$result = getResultArray($query, $GLOBALS['pdo'], $params);
	return isset($result) ? $result : null;
}

function getPictureRegister($pk, $table)
{
	$query = "SELECT * FROM {$table} WHERE pk = :pk";
	$params = array(
		":pk"=>$pk
		);
	$result = getResultArray($query, $GLOBALS['pdo'], $params);
	return isset($result) ? $result : null;
}

function getListingPictures($userId, $getMain=false, $listingId=null)
{
	if($listingId == null)
	{
		$listing = getListing($userId);
		if(empty($listing))
		{
			return null;
		}
		$listingId = $listing[0]['pk'];
	}

	$query = "SELECT * FROM result_picture WHERE result_picture.result_fk = :result_fk";
	if($getMain)
	{
		$query .= " AND main_picture = 1";
	}
	$params = array(
		":result_fk"=>$listingId
		);
	$result = getResultArray($query, $GLOBALS['pdo'], $params);
	return isset($result) ? $result : null;
}


function getPdo(){
	return $GLOBALS['pdo'];
}

function getAge($birthdate){
 return floor((time() - strtotime($birthdate))/31556926);
}

function formatDateString($dateString, $currrentFormatPattern, $newFormatPattern){
	$date = DateTime::createFromFormat($currrentFormatPattern, $dateString);
	$date = $date->format($newFormatPattern);
	return $date;
}

function checkLoggedIn(){
	if(!isLoggedIn()){
		goToUrl($GLOBALS['loginPageUrl']);
	}
}

function getListingCathegories(){
	$query = "SELECT pk, description FROM result_type";
	return getResultArray($query, $GLOBALS['pdo']);
}

function getListingBedTypes(){
	$query = "SELECT pk, description FROM result_bed_type";
	return getResultArray($query, $GLOBALS['pdo']);
}

function getListingCancellationTypes(){
	$query = "SELECT pk, description FROM result_cancellation_type";
	return getResultArray($query, $GLOBALS['pdo']);
}

function getListingRoomTypes(){
	$query = "SELECT pk, description FROM result_room_type";
	return getResultArray($query, $GLOBALS['pdo']);
}

function getGenders(){
	$query = "SELECT pk, description FROM user_gender";
	return getResultArray($query, $GLOBALS['pdo']);
}

function generateListedResultsArray($results){
	unset($_SESSION['listedResults']);
	$_SESSION['listedResults'] = array();
	foreach ($results as $r) {
	      $pk = $r['pk'];
	      $key = generateRandomString(10);
	      $_SESSION['listedResults'][$key] = $pk;
	}
}

function getHiddenListingPk($pk){
	return array_search($pk, $_SESSION['listedResults']); 
}

function emptyString($str){
	return !isset($str) || trim($str) == "";
}

function logout(){
	unset($_SESSION['loggedin']);
	session_destroy();
}

function getJSON($json){
	return json_encode($json);
}

function getURLFromReferer($url=""){
	$referer = $_SERVER['HTTP_REFERER'];
	$refererArray = explode("/", $referer);
	$refererArray[sizeof($refererArray)-1] = $url;
	$referer = implode("/", $refererArray);
	return $referer;
}

function doLogIn($userPk){
	$_SESSION['loggedin'] = true;
	$_SESSION['userLoggedIn'] = $userPk;
}

function ifsetor(&$variable, $default = null) {
    if (isset($variable)) {
        $tmp = $variable;
    } else {
        $tmp = $default;
    }
    return $tmp;
}

function displayTextIfExists($var, $tag){
	if(isset($var) && !emptyString($var)){
		return "<p>{$tag}: {$var}</p>";
	}
}

function displayImage($url){
	if(isset($url) && !emptyString($url)){
		return "<img src='{$url}' />";
	}
}

function printSelected($field, $value){
	return ($field != "" && $field == $value ? "selected":"");
}

function processUserPictures($files){
	$dir = createDirectory("img/profiles/"+getLoggedInUser());
	$filePaths = moveFiles($files, $dir);
	if($filePaths && !empty($filePaths)){
			$params = array(
				":user_fk"=>getLoggedInUser(),
				":picture_url"=>$filePaths["imageUrl"]
				);
		return executeInsert("user_picture", $params, $GLOBALS["pdo"]);
	}
	return "error";
}

function processResultPictures($files){
	$dir = createDirectory("img/profiles/"+getLoggedInUser());
	$filePaths = moveFiles($files, $dir);
	if($filePaths && !empty($filePaths)){
			$params = array(
				":result_fk"=>getListingId(),
				":picture_url"=>$filePaths["imageUrl"]
				);
		return executeInsert("result_picture", $params, $GLOBALS["pdo"]);
	}
	return "error";
}

function cropImage($url, $sufix, $params)
{

	//Copy the file
	$newUrl  = addSufixFilePath($url, $sufix);
	copy($url, $newUrl);

	$manipulator = new ImageManipulator($newUrl);
	$x1 = $params['x'];
	$x2 = $x1 + $params['width'];
	$y1 = $params['y'];
	$y2 = $y1 + $params['height'];
	$manipulator->crop($x1, $y1, $x2, $y2);
	$manipulator->save($newUrl);
	return true;
}

function addSufixFilePath($url, $sufix)
{
	$urlArray = explode("/", $url);
	$finalUrlPart = explode(".", $urlArray[sizeof($urlArray) - 1]);
	$finalUrlPart[0] .= $sufix;
	$urlArray[sizeof($urlArray) - 1] = implode(".", $finalUrlPart);

	$url = implode("/", $urlArray);

	return $url;
}

function deleteCroppedImage($table, $pk)
{
	$query = "SELECT * FROM {$table} WHERE pk = :pk";
	$params = array(
		":pk"=>$pk
		);

	$result = getResultArray($query, getPdo(), $params);
	$result = $result[0];
	//$croppedPictureUrl = (isset($result['cropped_picture_url'])) ? preg_replace("/&#?[a-z0-9]+;/i","",$result['cropped_picture_url']) : "";
	$croppedPictureUrl = (isset($result['cropped_picture_url'])) ? htmlspecialchars_decode($result['cropped_picture_url']) : "";
 	if($croppedPictureUrl != null && trim($croppedPictureUrl) != "")
	{
		unlink($croppedPictureUrl);
		$paramsSet = array(
			":cropped"=>0,
			":cropped_picture_url"=>""
			);
		$paramsWhere = array(
			":pk"=>$pk
			);
		executeUpdate($table, $paramsSet, $paramsWhere, getPdo());
	}
}

function getListing($user){
	$query = "SELECT result.*, address.postcode AS 'postcode',
	address.pk AS 'addressPk',
	 address.street AS 'street',
	  address.district AS 'district',
	   address.city AS 'city',
	    address.house AS 'house',
	     location.latitude AS 'lat',
	     location.pk AS 'locationPk',
	      location.longitude AS 'lng' FROM result INNER JOIN address ON result.address_fk = address.pk INNER JOIN location ON address.location_fk = location.pk WHERE user_fk = :user_fk";
	$params = array(
		":user_fk"=>$user
		);
	$result = getResultArray($query, getPdo(), $params);
	return $result;
}

function getListingId()
{
	$user = getLoggedInUser();
	$listing = getListing($user);
	return $listing[0]['pk'];
}

function getListingPicture()
{
	$picResults = getListingPictures(getLoggedInUser(), true);
	$mainPicUrl = null;
	if(!empty($picResults))
	{
		$cropped = $picResults[0]['cropped'] == 1;
		$mainPicUrl = $cropped ? $picResults[0]['cropped_picture_url'] : $picResults[0]['picture_url'];
	}
	$firstImageUrl = ($mainPicUrl == null) ? $GLOBALS['noPicImgUrl'] : $mainPicUrl;
	return $firstImageUrl;
}

function getProfilePicture($userPk = null)
{
	$userPk = ($userPk == null) ? getLoggedInUser() : $userPk;
	$picResults = getUserPictures($userPk, true);
	$mainPicUrl = null;
	if(!empty($picResults))
	{
		$cropped = $picResults[0]['cropped'] == 1;
		$mainPicUrl = $cropped ? $picResults[0]['cropped_picture_url'] : $picResults[0]['picture_url'];
	}
	$firstImageUrl = ($mainPicUrl == null) ? $GLOBALS['noPicImgUrl'] : $mainPicUrl;
	return $firstImageUrl;
}

function getListingPictureNotLoggedIn($listingId)
{
	$picResults = getListingPictures(null, true, $listingId);
	$mainPicUrl = null;
	if(!empty($picResults))
	{
		$cropped = $picResults[0]['cropped'] == 1;
		$mainPicUrl = $cropped ? $picResults[0]['cropped_picture_url'] : $picResults[0]['picture_url'];
	}
	$firstImageUrl = ($mainPicUrl == null) ? $GLOBALS['noPicImgUrl'] : $mainPicUrl;
	return $firstImageUrl;
}

?>